﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using HslCommunication;
using HslCommunication.Enthernet;
using HslCommunication.Profinet.Siemens;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace paraInterface
{
    public partial class ParaInterface : Form
    {

        #region public

        public List<Equip> equip=new List<Equip> ();

        #endregion

        public ParaInterface()
        {
            InitializeComponent();
            HslCommunication.Authorization.SetAuthorizationCode("b20aa83b-8a9e-4636-9f2a-12a4cfb53875");
        }
        private void ParaInterface_Load(object sender, EventArgs e)
        {
            WebApiStart();
            LoadPLCSetting();
        }

        #region LoadSetting
        private void LoadPLCSetting()
        {
            Ini setting = new Ini(Application.StartupPath + "\\Setting.ini");
            int totalequips = Convert.ToInt32( "0" + setting.ReadValue("Equips", "Total"));
            for (int i = 0; i < totalequips; i++)
            {
                Equip eqp = new Equip()
                {
                    TBG_DEVICE= setting.ReadValue("Equip" + (i + 1), "TBG_DEVICE"),
                    PLCType = setting.ReadValue("Equip" + (i + 1), "PLC"),
                };
                switch (eqp.PLCType)
                {
                    case "OMRON":
                        eqp.EquipPLC =new omronFinsUDPPLC();
                        eqp.EquipPLC.Port = Convert.ToInt32("0" + setting.ReadValue("Equip" + (i + 1), "Port"));
                        if (eqp.EquipPLC.Port == 0) eqp.EquipPLC.Port = 9600;
                        break;
                    case "OMRONTemp":
                        eqp.EquipPLC = new omronPLCTemper();
                        eqp.EquipPLC.Port = Convert.ToInt32("0" + setting.ReadValue("Equip" + (i + 1), "Port"));
                        if (eqp.EquipPLC.Port == 0) eqp.EquipPLC.Port = 9600;
                        break;
                    case "SIEMENS_A":
                        eqp.EquipPLC =new Siemens300PLC_A();
                        eqp.EquipPLC.Port = Convert.ToInt32("0" + setting.ReadValue("Equip" + (i + 1), "Port"));
                        if (eqp.EquipPLC.Port == 0) eqp.EquipPLC.Port = 102;
                        break;
                    case "SIEMENS_B":
                        eqp.EquipPLC =new Siemens300PLC_B();
                        eqp.EquipPLC.Port = Convert.ToInt32("0" + setting.ReadValue("Equip" + (i + 1), "Port"));
                        if (eqp.EquipPLC.Port == 0) eqp.EquipPLC.Port = 102;
                        break;
                    case "SIEMENS_C":
                        eqp.EquipPLC = new Siemens300PLC_C();
                        eqp.EquipPLC.Port = Convert.ToInt32("0" + setting.ReadValue("Equip" + (i + 1), "Port"));
                        if (eqp.EquipPLC.Port == 0) eqp.EquipPLC.Port = 102;
                        break;
                    default:
                        eqp.EquipPLC = new PLC();
                        break;
                }
                eqp.EquipPLC.IP = setting.ReadValue("Equip" + (i + 1), "IP");
                eqp.EquipPLC.ADD = setting.ReadValue("Equip" + (i + 1), "ADD");
                eqp.EquipPLC.SUB =Convert.ToByte( "0" + setting.ReadValue("Equip" + (i + 1), "SUB"));
                eqp.EquipPLC.DATALENTH =Convert.ToInt32( "0" + setting.ReadValue("Equip" + (i + 1), "DATALENTH"));
                if (eqp.EquipPLC.InitPLC())
                    equip.Add(eqp);
                else
                    pubcls.WriteLog(string.Format("设备：{0}的PLC初始化失败；设置的IP：{1}；设置的内存地址为：{2}；设置的数据长度为：{3}；设置的SUB为：{4}",
                        eqp.EquipPLC.IP, eqp.EquipPLC.ADD, eqp.EquipPLC.DATALENTH, eqp.EquipPLC.SUB));
            }

        }

        #endregion

        #region webapi
        private HttpServer httpServer;
        private void WebApiStart()
        {
            try
            {
                this.httpServer = new HttpServer();
                this.httpServer.HandleRequestFunc = HandleRequest;
                this.httpServer.Start(8090);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Web服务器加载失败！请以管理员身份运行。\n" + ex.Message);
                ExitApp();
            }
        }

        private string HandleRequest(HttpListenerRequest request, HttpListenerResponse response, string data)
        {
            if (request.HttpMethod == "GET")
            {
                return GetResponseJsonString("", "NG", "Using Post Method Please!", "0000003");
            }
            else if (request.HttpMethod == "POST")
            {
                if (request.RawUrl == "/SetEquipParameters")
                {
                    this.BeginInvoke(new MethodInvoker(() => { txt_TestJson.Text = DateTime.Now.ToString() + "\n" + data; }));
                    // Console.WriteLine(data);   // data 就是post上来的数据信息
                    try
                    {
                        bool isok = false;
                        pubcls.WriteLog(data);
                        jsonData _jsonData = JsonConvert.DeserializeObject<jsonData>(data);
                        Equip eqp = equip.Find(x => x.TBG_DEVICE == _jsonData.TBG_DEVICE);
                        if (eqp != null && eqp.EquipPLC.isRealPLC)
                        {

                            if (_jsonData.PARAMS.Length < eqp.EquipPLC.DATALENTH)
                                return GetResponseJsonString("", "NG", "Params's Length Error", "0000005");
                            else
                                Task.Run(() => {
                                    isok = eqp.EquipPLC.SendData2PLC(_jsonData);
                                }).Wait();
                            if (isok)
                            {
                                this.Invoke((EventHandler)delegate { lbl_msg.Text = "数据发送到" + _jsonData.TBG_DEVICE + "成功"; });
                                return GetResponseJsonString(_jsonData.TBG_DEVICE, "OK", "", "0000200");
                            }
                            else
                            {
                                this.Invoke((EventHandler)delegate { lbl_msg.Text = "数据发送到" + _jsonData.TBG_DEVICE + "失败"; });
                                return GetResponseJsonString("", "NG", "Send Data To PLC Error", "0000004");
                            }
                        }
                    }
                    catch (Exception)
                    { 
                        return GetResponseJsonString("", "NG", "Json Data Error", "0000001");
                    }
                }
                return GetResponseJsonString("", "NG", "Post Method Error", "0000002");
            }
            else
            {
                return GetResponseJsonString("", "NG", "Using Post Method Please!", "0000003");
            }
        }

        private string GetResponseJsonString(string sn, string result, string msg, string code)
        {
            JObject res = new JObject();
            res.Add(new JProperty("SN", sn));
            res.Add(new JProperty("RESULT", result));
            res.Add(new JProperty("MSG", msg));
            res.Add(new JProperty("MODEL_CODE", code));
            string s = JsonConvert.SerializeObject(res);
            pubcls. WriteLog(s);
            return s;
        }
        #endregion

        

        #region exit 
        private void ParaInterface_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            pnl_Exit.Visible = true;
        }

        private void btn_Exit_Cancel_Click(object sender, EventArgs e)
        {
            pnl_Exit.Visible = false;
        }

        private void btn_Exit_Confirm_Click(object sender, EventArgs e)
        {
            if (txt_PWD.Text == "yyrcl")
                ExitApp();
        }
        private void ExitApp()
        {
            Environment.Exit(0);
        }
        #endregion

    }
  


}
